import './SetUserTheme.scss'
import { useMount } from 'ahooks';
import { useRequest } from 'alova/client'
import { themeMapping, loadCSS } from '../../Config/devMapping'
import { Encrypt, Decrypt, GetIndexedDB, PutIndexedDB } from '../../Utils/IndexedDB'
import { useState } from 'react';
import { Http } from '../../Utils/Api';
import { themeStore } from '../../Config/zustand'



const SetUserTheme = () => {
    const [ThemeActive, setThemeActive] = useState()
    const { updateTheme, updateLogo, updateMenu, updateHead, updateBody } = themeStore()
    const { send } = useRequest(data => Http(data), { immediate: false })

    useMount(async () => {
        const dev = sessionStorage.getItem('dev')
        setThemeActive(dev)
    })

    const onSelect = (e) => {
        send({ method: 'post', url: 'users/UpdateUserTheme', params: { theme: e } }).then(() => {
            send({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: `THEME/${e}` } }).then(async res => {
                const common = await Decrypt(res)
                const { body, head, logo, menu, theme } = common
                await PutIndexedDB('project', common)
                JSON.stringify(await Encrypt(common))
                updateTheme(theme)
                updateLogo(logo)
                updateMenu(menu)
                updateHead(head)
                updateBody(body)
                sessionStorage.setItem('dev', e)
                loadCSS(themeMapping.find(v => v.value === e).css)
            })
        })
        setThemeActive(e)
    }

    return (
        <div className='SetUserTheme'>
            {themeMapping.map(({ label, value, img }) =>
                <div key={value} className={ThemeActive === value ? 'active' : ''} onClick={() => onSelect(value)}>
                    <img src={img} alt="" />
                    <div>{label}</div>
                </div>
            )}
        </div>
    )
}

export default SetUserTheme;